<template>
  <a-modal
    :maskClosable="false"
    title="操作"
    centered
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item style="display:none">
        <a-input v-decorator="['roleId']" />
      </a-form-item>

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="角色名称">
        <a-input v-decorator="['roleName', { rules: rules.roleName }]" placeholder="起一个名字" />
      </a-form-item>

      <!-- <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="显示顺序"
      >
        <a-input
          type="number"
          :min="1"
          v-decorator="['roleSort',{rules: [{ required: true, message: '请输入顺序' }]}]"
          placeholder="显示顺序"/>
      </a-form-item> -->

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态">
        <a-select
          :disabled="mdl.roleKey === 'admin'"
          v-decorator="['status', { initialValue: '0', rules: rules.status }]"
        >
          <a-select-option :value="'0'">正常</a-select-option>
          <a-select-option :value="'1'">禁用</a-select-option>
        </a-select>
      </a-form-item>
      <!-- <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="权限字符"
      >
        <a-input
          :disabled="mdl.roleKey === 'admin'"
          v-decorator="['roleKey',{rules: [{ required: false, message: '请输入权限字符' }]}]"
          placeholder="权限字符"/>
      </a-form-item> -->
      <!-- <a-divider /> -->
      <a-tabs type="card" v-model="tabsKey">
        <a-tab-pane :key="1" tab="web后台权限">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-tree
              checkable
              v-model="safeManagerPerCheckedKeys"
              @check="onSafeManagerPerCheck"
              :treeData="permissions"
            >
            </a-tree>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane :key="2" tab="小程序权限">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-tree checkable v-model="appletPerCheckedKeys" @check="onAppletPerCheck" :treeData="appPermissions">
            </a-tree>
          </a-form-item>
        </a-tab-pane>
      </a-tabs>
    </a-form>
  </a-modal>
</template>

<script>
import {
  getUserPermissions,
  getRolePermIdsWithSysType,
  saveAdminRole,
  getAppPermissions,
  getAppRolePermIdsWithSysType
} from '@/api/system/system'
import pick from 'lodash.pick'

export default {
  name: 'RoleModal',
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      visible: false,
      confirmLoading: false,
      mdl: {},
      tabsKey: 1,
      form: this.$form.createForm(this),
      permissions: [],
      appPermissions: [],
      treeCheck: false,
      appTreeCheck: false,
      pidSet: [],
      appPidSet: [],
      safeManagerPerCheckedKeys: [],
      halfSafeManagerPerCheckedKeys: [],
      appletPerCheckedKeys: [],
      halfAppletPerCheckedKeys: [],
      sysTypeInitialValue: 'OPERATING',
      rules: {
        roleName: [{ required: true, message: '请输入角色名称' }],
        roleSort: [{ required: true, message: '请输入顺序' }],
        roleKey: [{ required: true, message: '请输入权限字符' }],
        status: [{ required: true, message: '请选择状态' }],
        menuIds: [{ required: true, message: '请选择权限' }]
      }
    }
  },
  created() {
    this.loadPermissions(this.sysTypeInitialValue)
  },
  methods: {
    add() {
      this.form.resetFields()
      this.safeManagerPerCheckedKeys = []
      this.appletPerCheckedKeys = []
      this.pidSet = []
      this.edit({})
    },
    edit(record) {
      this.loadPermissions(this.sysTypeInitialValue).then(() => {
        if (record.roleId) {
          getRolePermIdsWithSysType(record.roleId, this.sysTypeInitialValue).then(res => {
            const pidSet = new Set(res.map(m => m.parentId).filter(id => id > 0))
            this.pidSet = pidSet
            // 因为antd 树插件勾选父节点会导致所有子节点选中,所以过滤所有父节点
            this.safeManagerPerCheckedKeys = res.map(m => m.menuId).filter(id => !pidSet.has(id))
            // this.appletPerCheckedKeys = []
          })

          getAppRolePermIdsWithSysType(record.roleId, this.sysTypeInitialValue).then(res => {
            const appPidSet = new Set(res.map(m => m.parentId).filter(id => id > 0))
            this.appPidSet = appPidSet
            // 因为antd 树插件勾选父节点会导致所有子节点选中,所以过滤所有父节点
            this.appletPerCheckedKeys = res.map(m => m.id).filter(id => !appPidSet.has(id))
          })
        }
        this.mdl = Object.assign({}, record)
        // 如果没有check过，半选节点是拿不到的，只能通过预先设置的pidSet获取
        this.treeCheck = false
        this.appTreeCheck = false
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.mdl, 'roleId', 'roleName', 'status', 'roleSort', 'roleKey'))
          // this.form.setFieldsValue(...record)
        })
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onSafeManagerPerCheck(keys, info) {
      if (!this.treeCheck) this.treeCheck = true
      this.safeManagerPerCheckedKeys = keys
      this.halfSafeManagerPerCheckedKeys = info.halfCheckedKeys
    },
    onAppletPerCheck(keys, info) {
      if (!this.appTreeCheck) this.appTreeCheck = true
      this.appletPerCheckedKeys = keys
      this.halfAppletPerCheckedKeys = info.halfCheckedKeys
    },
    onSelect(selectedKeys, info) {
      console.log('onSelect', info)
      this.selectedKeys = selectedKeys
    },
    loadPermissions(type) {
      var p = new Promise(async (resolve, reject) => {
        this.permissions = []
        this.appPermissions = []
        const res = await getUserPermissions({ sysType: type })
        const res2 = await getAppPermissions({ sysType: type })
        this.buildtree(res, this.permissions, 0)
        this.buildtree(res2, this.appPermissions, 0)
        resolve()
      })
      return p
    },
    buildtree(list, permissions, parentId) {
      list.forEach(item => {
        if (item.parentId === parentId) {
          const key = item.menuId || item.id
          var child = {
            key,
            title: item.menuName,
            children: []
          }
          this.buildtree(list, child.children, key)
          permissions.push(child)
        }
      })
    },
    handleOk(e) {
      const _this = this
      // 如果没有check过，半选节点是拿不到的，只能通过预先设置的pidSet获取
      const safeManagerPerKeys = this.treeCheck
        ? this.safeManagerPerCheckedKeys.concat(_this.halfSafeManagerPerCheckedKeys)
        : this.safeManagerPerCheckedKeys.concat(Array.from(_this.pidSet))
      if (!safeManagerPerKeys.length > 0) {
        _this.$message.warning('请至少选择一个web后台权限')
        return
      }
      const appPerKeys = this.appTreeCheck
        ? this.appletPerCheckedKeys.concat(_this.halfAppletPerCheckedKeys)
        : this.appletPerCheckedKeys.concat(Array.from(_this.appPidSet))

      // 触发表单验证
      this.form.validateFields((err, values) => {
        // 验证表单没错误
        if (!err) {
          values.menuIds = safeManagerPerKeys
          values.appMenuIds = appPerKeys
          values.roleKey = this.mdl.roleKey || 'user'
          _this.confirmLoading = true
          saveAdminRole(Object.assign(values))
            .then(res => {
              this.tabsKey = 1
              _this.$message.success('保存成功')
              _this.$emit('ok')
              _this.visible = false
            })
            .finally(() => {
              _this.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      this.tabsKey = 1
      this.visible = false
    }
  }
}
</script>

<style scoped></style>
